package com.liveneo.adapter.outinterface.util;

import java.io.IOException;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.liveneo.adapter.base.support.LogUtils;
import com.liveneo.adapter.outinterface.web.platform.ClaimInterface;

/**
  * 请求工具类
  * @author liveneo-shuqw
  * @date 2016年7月8日 下午6:08:04
  * Copyright: Copyright (c) 2016 
  * Company: 北京朗泰
  * @version 3.0
 */
public class HttpRequestUtil {
    private static Logger log = LoggerFactory.getLogger(HttpRequestUtil.class);

    /**
     * 发送json请求
     * 
     * @param url
     * @param result
     */
    public static <T> T postJson(String url, String param, String interfaceName, Class<T> classOfT) {
        // Create the POST object and add the parameters
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(param, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());
        httpPost.setEntity(entity);
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 发送结果
            HttpResponse response = client.execute(httpPost);
            // 判断状态码
            int statuscode = response.getStatusLine().getStatusCode();
            if (statuscode != 200) {
                throw new RuntimeException("请求地址错误或网络异常： statusCode：" + statuscode);
            }
            // 响应实体
            HttpEntity rsentity = response.getEntity();
            if (rsentity != null) {
                // 获取返回结果
                String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                log.info("请求接口名：【" + interfaceName + "】，朗泰核心接口返回信息：" + JsonUtils.fromBase64WithJson(result));
                return JsonUtils.fromJsonWithBase64(result, classOfT);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtils.info("请求 " + url + "异常 具体原因：" + e.getMessage() + " ，请求参数：" + param);
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    /**
      * @Title: postStringJson
      * @Description: 
      * @param @param url
      * @param @param param
      * @param @param interfaceName
      * @param @return 设定文件
      * @return String 返回类型
      * @throws
     */
    public static String postBase64StringJson(String url, String param, String interfaceName) {
        // Create the POST object and add the parameters
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(param, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());
        httpPost.setEntity(entity);
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 发送结果
            HttpResponse response = client.execute(httpPost);
            // 判断状态码
            int statuscode = response.getStatusLine().getStatusCode();
            if (statuscode != 200) {
                throw new RuntimeException("请求地址错误或网络异常： statusCode：" + statuscode);
            }
            // 响应实体
            HttpEntity rsentity = response.getEntity();
            if (rsentity != null) {
                // 获取返回结果
                String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                log.info("请求接口名：【" + interfaceName + "】，朗泰核心接口返回信息：" + JsonUtils.fromBase64WithJson(result));
                return JsonUtils.fromBase64WithJson(result);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtils.info("请求 " + url + "异常 具体原因：" + e.getMessage() + " ，请求参数：" + param);
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    public static <T> T postJsonNotBase64(String url, String param, String interfaceName, Class<T> classOfT) {
        // Create the POST object and add the parameters
        HttpPost httpPost = new HttpPost(url);
        StringEntity entity = new StringEntity(param, Consts.UTF_8);
        entity.setContentType(ContentType.APPLICATION_JSON.toString());
        httpPost.setEntity(entity);
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 发送结果
            HttpResponse response = client.execute(httpPost);
            // 状态码
            int statuscode = response.getStatusLine().getStatusCode();
            if (statuscode != 200) {
                throw new RuntimeException("请求地址错误或网络异常： statusCode：" + statuscode);
            }
            // 响应实体
            HttpEntity rsentity = response.getEntity();
            if (rsentity != null) {
                // 获取返回结果
                String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                log.info("请求接口名：【" + interfaceName + "】，朗泰核心接口返回信息：" + result);
                return JsonUtils.fromJson(result, classOfT);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtils.info("请求 " + url + "异常 具体原因：" + e.getMessage() + " ，请求参数：" + param);
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    /**
      * @Title: getJson
      * @Description: 发送消息
      * @param @param url
      * @param @param param
      * @param @param interfaceName
      * @param @param classOfT
      * @param @return 设定文件
      * @return T 返回类型
      * @throws
     */
    public static <T> T getJson(String url, String param, String interfaceName, Class<T> classOfT) {
        // Create the Get object and add the parameters
        HttpGet httpGet = new HttpGet(url + "?data=" + param);
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            // 发送结果
            HttpResponse response = client.execute(httpGet);
            // 状态码
            int statuscode = response.getStatusLine().getStatusCode();
            if (statuscode != 200) {
                throw new RuntimeException("请求地址错误或网络异常：statusCode：" + statuscode);
            }
            // 响应实体
            HttpEntity rsentity = response.getEntity();
            if (rsentity != null) {
                // 获取返回结果
                String result = EntityUtils.toString(response.getEntity(), Consts.UTF_8);
                LogUtils.info("请求接口名：【" + interfaceName + "】，APP适配层消息接口返回信息：" + JsonUtils.fromBase64WithJson(result));
                return JsonUtils.fromJsonWithBase64(result, classOfT);
            }
        } catch (Exception e) {
            // e.printStackTrace();
            LogUtils.info("请求 " + url + "异常 具体原因：" + e.getMessage() + " ，请求参数：" + param);
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return null;
    }

    /**
      * @Title: sendMessageInfo
      * @Description: 消息实体封装
      * @param @param caseNo 案件号
      * @param @param type  消息类型
      * @param @param userCode 查勘员号
      * @param @param mobile 手机号
      * @param @param clientType 个推端
      * @param @param msg 设定文件 消息
      * @return void 返回类型
      * @throws
     */
    public static void sendMessageInfo(String caseNo, String type, String userCode, String mobile, int clientType, String msg) {
        Message message = new Message();
        message.setCaseNo(caseNo);
        message.setMsgUUID("CK-" + UUIDUtils.uuid());
        message.setNewstype(type);// 核损完通知
        message.setContent(msg);
        message.setUserCode(userCode);
        message.setUserMobile(mobile);
        message.setClientType(StringUtil.numberToChar(clientType));
        ClaimInterface.sendMessageInfo(message);
    }
}
